<template>
	<view class="page-wrap">
		<view>
			<view class="topbar">
				<image class="logo" src="/static/logo.png"></image>
			</view>
		</view>
        <uni-section title="今日汇总" type="line">
			<uni-list>
				<uni-list-item title="订单数量" :rightText="totalBillCnt" />
				<uni-list-item title="金额总计" :rightText="`￥${totalBillAmount}`" />
				<uni-list-item title="平均客单价" :rightText="`￥${avrBillAmount}`" />
			</uni-list>
		</uni-section>
        <uni-section title="历史汇总" type="line">
			<uni-list>
				<uni-list-item v-for="(item, index) in dailySums" :key="index" :title="item.date" :rightText="`￥${item.billAmount} / ${item.billNum}笔`" />
			</uni-list>
		</uni-section>
        <uni-section title="商品管理" type="line" padding>
            <view class="grid">
                <uni-grid :column="4" :highlight="true" @change="onGoodsGridChange">
                    <uni-grid-item :index="0">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="cloud-download" :size="30" color="#f1d145" />
                            <text class="text">导入商品</text>
                        </view>
                    </uni-grid-item>
                    <uni-grid-item :index="1">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="weixin" :size="30" color="#f1d145" />
                            <text class="text">导出商品</text>
                        </view>
                    </uni-grid-item>
                    <uni-grid-item :index="2">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="trash" :size="30" color="#f1d145" />
                            <text class="text">清空商品</text>
                        </view>
                    </uni-grid-item>
                    <uni-grid-item :index="3">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="refreshempty" :size="30" color="#f1d145" />
                            <text class="text">恢复商品</text>
                        </view>
                    </uni-grid-item>
                </uni-grid>
            </view>
        </uni-section>
        <uni-section title="订单管理" type="line" padding>
            <view class="grid">
                <uni-grid :column="4" :highlight="true" @change="onBillsGridChange">
                    <uni-grid-item :index="0">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="cloud-download" :size="30" color="#f1d145" />
                            <text class="text">导入订单</text>
                        </view>
                    </uni-grid-item>
                    <uni-grid-item :index="1">
                        <view class="grid-item-box" style="background-color: #fff;">
                            <uni-icons type="weixin" :size="30" color="#f1d145" />
                            <text class="text">导出订单</text>
                        </view>
                    </uni-grid-item>
                </uni-grid>
            </view>
        </uni-section>
    </view>
</template>

<script setup lang="ts">
import moment from 'moment';
import { computed } from 'vue';

interface IDailySum {
    date: string
    billAmount: number
    billNum: number
}

const onGoodsGridChange = (payload: ui.GridPayload) => {
    if (payload.detail.index == 0) {
        importGoods();
    } else if (payload.detail.index == 1) {
        shareGoods();
    } else if (payload.detail.index == 2) {
        resetGoods();
    } else if (payload.detail.index == 3) {
        useOldGoods();
    }
}

const importGoods = () => {
    uni.getClipboardData({
        success(res) {
            console.log('clipboard data:', res.data);
            if (res.data.startsWith(engine.dataMgr.Prefix)) {
                const s = res.data.substring(engine.dataMgr.Prefix.length);
                try {
                    const goods: engine.GoodInfo[] = JSON.parse(s);
                    if (!goods.length) {
                        uni.showToast({
                            title: '商品数量为0！导入失败！',
                            icon: 'error'
                        });
                        return;
                    }
                    uni.showModal({
                        content: `是否导入${goods[0].name}等${goods.length}种商品数据？`,
                        success(result) {
                            if (result.confirm) {
                                engine.dataMgr.addGoods(goods);
                                engine.dataMgr.saveGoods();
                            }
                        },
                    });
                } catch (e) {
                    console.error('parse clipboard data failed:', s);
                }
            } else {
                uni.showModal({
                    content: '是否导入默认的商品数据？',
                    success(result) {
                        if (result.confirm) {
                            engine.dataMgr.useDefaultGoods();
                            engine.dataMgr.saveGoods();
                        }
                    },
                });
            }
        },
        fail(result) {
            console.error('get clipboard data failed:', result);
            uni.showToast({
                title: '导入失败',
                icon: 'error'
            });
        },
    });
}

const shareGoods = () => {
	uni.setClipboardData({
		data: engine.dataMgr.Prefix + JSON.stringify(engine.dataMgr.goods.value),
		showToast: true,
		success(result) {
			uni.showToast({
				title: '商品信息已复制',
				icon: 'success'
			});
		},
		fail(result) {
			uni.showToast({
				title: '商品信息复制失败',
				icon: 'error'
			});			
		},
	})
}

const resetGoods = () => {
	uni.showModal({
		content: '是否清空所有商品？',
		success(result) {
			if (result.confirm) {
				engine.dataMgr.resetGoods();
                engine.dataMgr.saveGoods();
			}
		}
	});
}

const useOldGoods = () => {
	uni.showModal({
		content: '是否恢复上一次的商品？',
		success(result) {
			if (result.confirm) {
				engine.dataMgr.useOldGoods();
                engine.dataMgr.saveGoods();
			}
		}
	});
}

const onBillsGridChange = (payload: ui.GridPayload) => {
    console.log('onBillsGridChange:', payload);
    if (payload.detail.index == 0) {
        importBills();
    } else if (payload.detail.index == 1) {
        shareBills();
    }
}

const importBills = () => {
	uni.getClipboardData({
		success(res) {
			console.log('clipboard data:', res.data);
			if (res.data.startsWith(engine.dataMgr.BillPrefix)) {
				const s = res.data.substring(engine.dataMgr.BillPrefix.length);
				try {
					const bills = JSON.parse(s) as engine.BillInfo[];
					uni.showModal({
						content: '是否导入订单数据？',
						success(result) {
							if (result.confirm) {
								engine.dataMgr.addBills(bills)
							}
						},
					})
				} catch (e) {
					console.error('parse clipboard data failed:', s);
				}
			}
		},
		fail(result) {
			console.error('get clipboard data failed:', result);
			uni.showToast({
				title: '导入失败',
				icon: 'error'
			});
		},
	});
}

const shareBills = () => {
	uni.setClipboardData({
		data: engine.dataMgr.BillPrefix + JSON.stringify(engine.dataMgr.bills.value),
		showToast: true,
		success(result) {
			uni.showToast({
				title: '订单信息已复制',
				icon: 'success'
			});
		},
		fail(result) {
			uni.showToast({
				title: '订单信息复制失败',
				icon: 'error'
			});			
		},
	})
}

const totalBillCnt = computed(() => {
    return engine.dataMgr.bills.value.length;
})
const totalBillAmount = engine.dataMgr.totalBillAmount;
const avrBillAmount = computed(() => {
    return (totalBillAmount.value / totalBillCnt.value).toFixed(1)
});
const dailySums = computed(() => {
    const dss: IDailySum[] = [];
    const dsMap: Record<string, IDailySum> = {};
    for (const b of engine.dataMgr.bills.value) {
        const date = moment(b.time).format('YYYY-MM-DD');
        let ds = dsMap[date];
        if (ds == null) {
            dsMap[date] = ds = { date, billAmount: b.totalAmount, billNum: 1 };
            dss.push(ds);
        } else {
            ds.billAmount += b.totalAmount;
            ds.billNum++;
        }
    }
    console.log('dss: ', dss);
    return dss;
})

</script>

<style lang="scss">

.grid {
    padding-left: 10px;
    padding-right: 10px;
}

.grid-item-box {
    flex: 1;
    // position: relative;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15px 0;
}

</style>